package cn.wizzer.app.user.modules.service.impl;

import cn.wizzer.app.match.modules.models.constant.RedisKey;
import cn.wizzer.app.sys.modules.models.SysParam;
import cn.wizzer.app.sys.modules.services.SysConfigService;
import cn.wizzer.app.sys.modules.services.SysParamService;
import cn.wizzer.app.user.modules.models.UserRestriction;
import cn.wizzer.app.user.modules.models.vo.UserRestrictionVo;
import cn.wizzer.app.user.modules.services.UserRestrictionService;
import cn.wizzer.framework.base.service.BaseServiceImpl;
import cn.wizzer.framework.base.service.CommonDBService;
import cn.wizzer.framework.page.Pagination;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;

@IocBean(args = {"refer:dao"})
@Service(interfaceClass = UserRestrictionService.class)
public class UserRestrictionServiceImpl extends BaseServiceImpl<UserRestriction> implements UserRestrictionService {
    public UserRestrictionServiceImpl(Dao dao) {
        super(dao);
    }

    @Reference
    @Inject
    private SysConfigService sysConfigService;

    @Reference
    @Inject
    private SysParamService sysParamService;

    @Inject
    private CommonDBService commonDBService;

    @Inject
    private RedisService redisService;

    @Override
    public Pagination listPage(int pageNumber, int pageSize, String searchKeyword) {
        Sql sql = Sqls.create("select u.nickName,u.phone,u.id as uId, r.* " +
                " from user_restriction r ");
        Sql countSql = Sqls.create("select count(1) from user_restriction r ");
        Sql joinSql = Sqls.create("left join user u on r.user_id = u.id " +
                "$condition ");
        Cnd cnd = Cnd.NEW();
        if (Strings.isNotBlank(searchKeyword)) {
            searchKeyword = "%" + searchKeyword + "%";
            cnd.and(Cnd.exps("u.phone", "like", searchKeyword)
                    .or("u.nickName", "like", searchKeyword));
        }
        joinSql.setCondition(cnd);
        sql.appendSourceSql(joinSql.toString());
        sql.appendSourceSql("order by r.opAt desc");
        countSql.appendSourceSql(joinSql.toString());
        return commonDBService.listPage(UserRestrictionVo.class, pageNumber, pageSize, sql.toString(), countSql.toString());
    }

    @Override
    public UserRestriction fetchByUserId(String userId) {
        UserRestriction fetch = this.fetch(Cnd.where("user_id", "=", userId));
        //此时-看看最大限制问题
        int totalRateMax = sysParamService.fetch().getTotalRateMax();
        int selfRateMax = sysParamService.fetch().getSelfRateMax();
        int superRateMax = sysParamService.fetch().getSuperRateMax();
        if (fetch.getSelfRate() > selfRateMax || fetch.getSuperRate() > superRateMax || (fetch.getSelfRate() + fetch.getSuperRate()) > totalRateMax) {
            //违规点处理
            fetch.setSuperRate(superRateMax);
            int i = totalRateMax - superRateMax;
            //防止上级反比超过总反比值
            if (i < 0) {
                fetch.setSelfRate(0);
            } else {
                //用户自身返水与上级返利和是否超过总限制
                if (i < selfRateMax) {
                    fetch.setSelfRate(i);
                } else {
                    fetch.setSelfRate(selfRateMax);
                }

            }
        }

        return fetch;
    }

    /**
     * 批量恢复默认限制
     *
     * @param ids
     * @return
     */
    @Override
    public Boolean batchRestriction(String[] ids, String opBy) {
        SysParam sysParam = sysParamService.fetch();
        this.dao().update(UserRestriction.class, Chain.make("timeMinRestriction", sysParam.getTimeMinRestriction())
                .add("timeMaxRestriction", sysParam.getTimeMaxRestriction())
                .add("dayRestriction", sysParam.getDayRestriction())
                .add("totalRestriction", sysParam.getTotalRestriction())
                .add("selfRate", sysParam.getSelfRate())
                .add("superRate", sysParam.getSuperRate())
                .add("giftRate", sysParam.getGiftRate())
                .add("viewRate", sysParam.getViewRate())
                .add("opAt", Times.getTS())
                .add("opBy", opBy), Cnd.where("id", "in", ids));
        //循环查询数据更新缓存
        for (String id : ids) {
            saveCache(fetch(id));
        }
        return true;
    }

    /**
     * 初始化用户限制缓存
     *
     * @param userId
     * @return
     */
    @Override
    public UserRestriction initCache(String userId) {
        //缓存中取出用户限制数据
        UserRestriction userRestriction = JSONObject.parseObject(redisService.hget(RedisKey.USER_RESTRICTION, userId), UserRestriction.class);
        if (userRestriction == null) {
            userRestriction = fetchByUserId(userId);
            //保存缓存
            saveCache(userRestriction);
        }
        return userRestriction;
    }

    /**
     * 保存缓存
     *
     * @param userRestriction
     */
    @Override
    public void saveCache(UserRestriction userRestriction) {
        redisService.hset(RedisKey.USER_RESTRICTION, userRestriction.getUserId(), JSONObject.toJSONString(userRestriction));
    }
}